const express = require("express");
const app = express();
const config = require("./config/default.js");
const jwt = require("./lib/jwt.js");

// 加入静态文件
app.use(express.static(__dirname + "/data"));

// 设置跨域
const cors = require("cors");
app.use(cors());

// 添加请求日志中间件，帮助调试
app.use((req, res, next) => {
  console.log(`[${new Date().toLocaleTimeString()}] ${req.method} ${req.url}`);
  next();
});

// 解析前端的数据 - 确保这些中间件在token处理前执行
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// token处理 - 完全重写
app.use((req, res, next) => {
  // 白名单路径 - 不需要token验证的路由
  const whiteList = ['/login', '/signin', '/register', '/isRegister', '/upload'];
  
  // 跳过白名单路径和GET请求
  if (whiteList.some(path => req.url.startsWith(path)) || req.method === 'GET') {
    return next();
  }
  
  try {
    // 从多个位置尝试获取token
    const token = 
      (req.body && req.body.token) || 
      (req.query && req.query.token) || 
      (req.headers && (
        req.headers.authorization || 
        req.headers['x-access-token']
      ));
    
    if (!token) {
      console.log('请求缺少token:', req.url);
      return res.status(401).send({
        code: 401,
        message: "请提供token"
      });
    }
    
    // 验证token
    const isok = jwt.verifyToken(token);
    if (isok === 1) {
      return next();
    } else {
      return res.status(401).send({
        code: 300,
        message: "token无效或已过期"
      });
    }
  } catch (error) {
    console.error("Token验证错误:", error);
    return res.status(500).send({
      code: 500,
      message: "服务器错误"
    });
  }
});

// 引入路由
require("./routers/index")(app);
require("./routers/files")(app);

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error("全局错误:", err);
  res.status(500).send({
    code: 500,
    message: "服务器内部错误"
  });
});

// 启动服务器
app.listen(config.port, () => {
  console.log(`服务器运行在 http://localhost:${config.port}`);
});
